package com.liyuxiang.graph.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class ConversationHandlingService {
    
    private static final Logger logger = LoggerFactory.getLogger(ConversationHandlingService.class);
    private final ChatClient chatClient;
    private final ObjectMapper objectMapper;
    
    @Autowired
    private AiCacheService cacheService;
    
    // AI智能对话处理提示词 - 完全依赖AI判断，支持上下文感知
    private static final String CONVERSATION_HANDLING_PROMPT = """
            你是专业的智能问诊助手，擅长温暖专业地引导用户进行健康咨询。
            
            用户输入: {query}
            对话上下文: {conversationContext}
            当前对话阶段: {conversationStage}
            历史问题数: {questionCount}
            
            请智能分析用户输入并生成适合的回复：
            
            请特别注意：
            1. 根据对话上下文调整回复的语调和内容
            2. 考虑用户的情绪状态和真实意图
            3. 针对不同的对话阶段采用不同的引导策略
            4. 区分真实的医疗咨询和闲聊测试
            5. 根据问题数量调整回复的深入程度
            
            可能的对话类型：
            - 打招呼: 友好回应，自然引导到健康话题
            - 功能询问: 介绍症状分析和科室推荐功能
            - 闲聊: 简单回应后转向健康话题
            - 测试: 展示专业性，鼓励真实咨询
            - 情绪: 理解并询问相关身体症状
            - 症状咨询: 专业引导，收集症状细节
            
            返回JSON格式：
            {
              "response": "智能生成的回复内容",
              "conversationType": "对话类型",
              "guidanceLevel": "low/medium/high",
              "tone": "语调风格",
              "nextActionSuggestion": "建议的下一步行动",
              "engagementStrategy": "互动策略描述",
              "contextAwareness": "上下文理解情况"
            }
            """;
    
    public ConversationHandlingService(@Qualifier("simpleCharClientBuilder") ChatClient.Builder simpleCharClientBuilder, ObjectMapper objectMapper) {
        this.chatClient = simpleCharClientBuilder.build();
        this.objectMapper = objectMapper;
    }
    
    public ConversationHandlingResult handleConversation(String query, List<String> conversationHistory, String userId) {
        return handleConversation(query, conversationHistory, userId, "", 0);
    }
    
    /**
     * 智能对话处理 - 支持上下文感知
     */
    public ConversationHandlingResult handleConversation(String query, List<String> conversationHistory, 
                                                       String userId, String conversationStage, int questionCount) {
        long startTime = System.currentTimeMillis();
        logger.info("开始AI对话处理 - 用户ID: {}, 输入: {}, 阶段: {}, 问题数: {}", 
                   userId, query, conversationStage, questionCount);
        
        // 构建对话上下文
        String conversationContext = buildConversationContext(conversationHistory);
        
        // 检查缓存（包含对话阶段）
        ConversationHandlingResult cachedResult = cacheService.getConversationCache(
            query, userId, conversationStage + questionCount, ConversationHandlingResult.class);
        if (cachedResult != null) {
            long duration = System.currentTimeMillis() - startTime;
            logger.info("对话处理缓存命中 - 用户ID: {}, 耗时: {}ms", userId, duration);
            return cachedResult;
        }
        
        try {
            // 构建智能提示词
            String prompt = CONVERSATION_HANDLING_PROMPT
                    .replace("{query}", query)
                    .replace("{conversationContext}", conversationContext)
                    .replace("{conversationStage}", conversationStage)
                    .replace("{questionCount}", String.valueOf(questionCount));
            
            logger.info("发送AI智能对话处理请求 - 用户ID: {}", userId);
            
            String aiResponse = chatClient.prompt()
                    .user(prompt)
                    .call()
                    .content();
            
            ConversationHandlingResult result = parseConversationHandlingResponse(aiResponse);
            
            // 缓存结果（包含阶段信息）
            cacheService.setConversationCache(query, userId, conversationStage + questionCount, result);
            
            long duration = System.currentTimeMillis() - startTime;
            logger.info("AI对话处理完成 - 用户ID: {}, 类型: {}, 耗时: {}ms", 
                       userId, result.getConversationType(), duration);
            
            return result;
            
        } catch (Exception e) {
            logger.error("AI对话处理失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return createMinimalFallback(query, userId);
        }
    }

    /**
     * 异步对话处理
     */
    @Async("aiTaskExecutor")
    public CompletableFuture<ConversationHandlingResult> handleConversationAsync(String query, List<String> conversationHistory, String userId) {
        return CompletableFuture.completedFuture(handleConversation(query, conversationHistory, userId));
    }
    
    private ConversationHandlingResult parseConversationHandlingResponse(String response) {
        try {
            int startIndex = response.indexOf('{');
            int endIndex = response.lastIndexOf('}') + 1;
            
            if (startIndex >= 0 && endIndex > startIndex) {
                String jsonStr = response.substring(startIndex, endIndex);
                JsonNode jsonNode = objectMapper.readTree(jsonStr);
                
                String responseText = jsonNode.get("response").asText();
                String conversationType = jsonNode.get("conversationType").asText("其他");
                String guidanceLevel = jsonNode.get("guidanceLevel").asText("moderate");
                String tone = jsonNode.get("tone").asText("friendly");
                String nextActionSuggestion = jsonNode.get("nextActionSuggestion").asText("描述症状");
                String engagementStrategy = jsonNode.get("engagementStrategy").asText("友好引导");
                
                return new ConversationHandlingResult(responseText, conversationType, guidanceLevel, 
                        tone, nextActionSuggestion, engagementStrategy, true);
            }
        } catch (Exception e) {
            logger.warn("解析对话处理JSON失败，尝试文本解析: {}", e.getMessage());
        }
        
        return parseTextConversationResponse(response);
    }
    
    /**
     * 简单的文本响应解析 - 作为JSON解析失败的备用方案
     */
    private ConversationHandlingResult parseTextConversationResponse(String response) {
        String lowerResponse = response.toLowerCase();
        String conversationType;
        String responseText = response.length() > 200 ? response.substring(0, 200) + "..." : response;
        
        // 基于响应内容进行简单的类型判断
        if (lowerResponse.contains("打招呼") || lowerResponse.contains("你好")) {
            conversationType = "打招呼";
        } else if (lowerResponse.contains("功能") || lowerResponse.contains("介绍")) {
            conversationType = "功能询问";
        } else if (lowerResponse.contains("测试")) {
            conversationType = "测试";
        } else if (lowerResponse.contains("症状") || lowerResponse.contains("医疗")) {
            conversationType = "症状咨询";
        } else {
            conversationType = "其他";
        }
        
        return new ConversationHandlingResult(responseText, conversationType, "moderate", 
                "friendly", "描述症状", "基于文本内容的简单响应分析", false);
    }
    
    /**
     * 构建对话上下文摘要
     */
    private String buildConversationContext(List<String> conversationHistory) {
        if (conversationHistory == null || conversationHistory.isEmpty()) {
            return "无对话历史";
        }
        
        // 取最后3轮对话作为上下文
        int start = Math.max(0, conversationHistory.size() - 6);
        List<String> recentHistory = conversationHistory.subList(start, conversationHistory.size());
        
        StringBuilder context = new StringBuilder();
        for (String message : recentHistory) {
            context.append(message).append("\n");
        }
        
        return context.toString().trim();
    }
    
    /**
     * 最小化备用对话处理 - 只在AI完全失败时使用
     */
    private ConversationHandlingResult createMinimalFallback(String query, String userId) {
        logger.warn("使用最小化备用对话处理 - 用户ID: {}, AI服务不可用", userId);
        
        // 非常简单的备用回复
        String response = "抱歉，系统暂时无法理解您的输入。请稍后重试或描述您的具体症状。";
        String conversationType = "系统错误";
        
        return new ConversationHandlingResult(response, conversationType, "low", 
                "apologetic", "重新输入", "AI服务不可用的备用策略", false);
    }
    
    public static class ConversationHandlingResult {
        private final String response;
        private final String conversationType;
        private final String guidanceLevel;
        private final String tone;
        private final String nextActionSuggestion;
        private final String engagementStrategy;
        private final boolean fullAiAnalysis;
        
        public ConversationHandlingResult(String response, String conversationType, String guidanceLevel, 
                                        String tone, String nextActionSuggestion, String engagementStrategy, boolean fullAiAnalysis) {
            this.response = response;
            this.conversationType = conversationType;
            this.guidanceLevel = guidanceLevel;
            this.tone = tone;
            this.nextActionSuggestion = nextActionSuggestion;
            this.engagementStrategy = engagementStrategy;
            this.fullAiAnalysis = fullAiAnalysis;
        }
        
        // Getters
        public String getResponse() { return response; }
        public String getConversationType() { return conversationType; }
        public String getGuidanceLevel() { return guidanceLevel; }
        public String getTone() { return tone; }
        public String getNextActionSuggestion() { return nextActionSuggestion; }
        public String getEngagementStrategy() { return engagementStrategy; }
        public boolean isFullAiAnalysis() { return fullAiAnalysis; }
    }
}